﻿Public Class ClassSale
    Public Shared Function addSale(ByVal inNo As String, ByVal corpid As Integer, ByVal empid As Integer, ByVal ship As Double, ByVal amount As Double, ByVal disc As Int16, ByVal vat As Int16, ByVal total As Double, ByVal dgv As DataGridView, ByVal status As Int16, ByVal pay As Double, ByVal deposit As Double)
        Dim sql1 = <sql>
                    insert into tbl_sale(invoice_code,sale_date,corporate_id,employee_id,shipping_rate,amount,deposit,discount,exchange_rate_detail_id,vat_rate,total_price,active)
                    value(@in,@date,@corpid,@empid,@ship,@amount,@deposit,@discount,4,@vat,@total,1)
                  </sql>
        Dim sql3 = <sql>
                    insert into tbl_sale_payment(sale_id,payment_date,payment_amount,exchange_rate_detail_id,payment_status,active)
                    value(@sid,@date,@pay,4,@status,1)
                 </sql>
        Dim sql2 = <sql>
                    insert into tbl_sale_detail(sale_id,item_id,qty,price,descount,cost)
                    value(@sid,@item,@qty,@price,@disc,@total) 
                 </sql>


        Try
            Cmd.Begin()
            Cmd.Parameters("@in") = inNo
            Cmd.Parameters("@date") = Now.Date
            Cmd.Parameters("@corpid") = corpid
            Cmd.Parameters("@empid") = empid
            Cmd.Parameters("@ship") = ship
            'Cmd.Parameters("@exchange") = exchange
            Cmd.Parameters("@amount") = amount
            Cmd.Parameters("@deposit") = deposit
            Cmd.Parameters("@discount") = disc
            Cmd.Parameters("@vat") = vat
            Cmd.Parameters("@total") = total
            Cmd.ExecuteNonQuery(sql1)

            Dim sid = Cmd.ExecuteScalar("select MAX(sale_id) from tbl_sale")

            Cmd.Parameters("@sid") = sid
            Cmd.Parameters("@date") = Now.Date
            Cmd.Parameters("@pay") = pay
            'Cmd.Parameters("@exchange") = exchange
            'Cmd.Parameters("@desc") = desc
            Cmd.Parameters("@status") = status
            Cmd.ExecuteNonQuery(sql3)

            For i = 0 To dgv.Rows.Count - 1
                Cmd.Parameters("@sid") = sid
                Cmd.Parameters("@item") = dgv.Rows(i).Cells("item_id").Value
                Cmd.Parameters("@qty") = dgv.Rows(i).Cells("item_qty").Value
                Cmd.Parameters("@price") = dgv.Rows(i).Cells("item_price").Value
                Cmd.Parameters("@disc") = dgv.Rows(i).Cells("item_discount").Value
                Cmd.Parameters("@total") = dgv.Rows(i).Cells("amount").Value
                Cmd.ExecuteNonQuery(sql2)
            Next
            myMsgbox.show("Add new Sale Success!!!", "New Sale")
            Cmd.Commit()
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
            Cmd.Rollback()
            Return False
        End Try
    End Function
End Class
